package com.zja.servlet;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.zja.model.JsonResponse;
import com.zja.model.KnowledgeBase;
import com.zja.model.User;
import com.zja.service.Impl.KnowledgeBaseServiceImpl;
import com.zja.service.KnowledgeBaseService;
import com.zja.util.JsonUtil;
import com.zja.util.ServletUtil;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
 * @author JA
 * @date: 2025/5/3
 * description:获取我创建的知识库列表
 */
@WebServlet("/api/knowledgebase/my")
public class MyKnowledgeBasesServlet extends HttpServlet {
    private final KnowledgeBaseService knowledgeBaseService = new KnowledgeBaseServiceImpl();


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");

        HttpSession session = req.getSession(false);
        if (session == null || session.getAttribute("currentUser") == null) {
            // 未登录，返回错误信息
            ServletUtil.writeJsonResponse(resp, JsonResponse.error("请先登录"));
            return;
        }

        User currentUser = (User) session.getAttribute("currentUser");
        List<KnowledgeBase> all = knowledgeBaseService.getAll();
        List<KnowledgeBase> mine = new ArrayList<>();

        // 过滤出当前用户创建的知识库
        for (KnowledgeBase kb : all) {
            if (kb.getCreatorId().equals(currentUser.getId())) {
                mine.add(kb);
            }
        }

        // 返回当前用户创建的知识库列表
        ServletUtil.writeJsonResponse(resp, JsonResponse.success("获取成功", mine));
    }
}
